<?php
	/**
	 * Elgg europass : Add action
	 * 
	 * @package ElggEuropass
	 * @link http://e-portfolio.uvsq.fr/
	 */

	// Make sure we're logged in (send us to the front page if not)
  // Don't check usual action_gatekeeper(); as this is not a proper action
	gatekeeper();
  
	// Get input data
  $xmlString = get_input('EUROPASSCV', '', false);
	// The default access level is private
  $access = 0;

	// Cache to the session
  $_SESSION['xml'] = $xmlString;
	
  if (empty($xmlString))
  {
    register_error(elgg_echo("europass:error"));
    js_redirect('mod/europass/edit.php');
  }
  else
  {
 
		// Initialise a new ElggObject
		$europass = new ElggObject();
		$europass->subtype = "europass";
		$europass->owner_guid = $_SESSION['user']->getGUID();
		$europass->access_id = $access;
		
		$europass->title = sprintf(elgg_echo("europass:title"), $_SESSION['user']->name);
		$europass->description = sprintf(elgg_echo("europass:title"), $_SESSION['user']->name);

		if (!$europass->save()) {
			register_error(elgg_echo("europass:error"));
			js_redirect('mod/europass/edit.php');
    }
    
    $xml = new SimpleXMLElement($xmlString);
  
		// Get info from XML
		// identification
		$result = $xml->xpath('//europass:learnerinfo/identification/firstname');
		$europass->firstname = fixEncoding($result[0]);
		$result = $xml->xpath('//europass:learnerinfo/identification/lastname');
		$europass->lastname = fixEncoding($result[0]);
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/addressLine');
		$europass->addressLine = fixEncoding($result[0]);
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/municipality');
		$europass->municipality = fixEncoding($result[0]);
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/postalCode');
		$europass->postalCode = $result[0];
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/country/code');
		$europass->countryCode = $result[0];
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/country/label');
		$europass->countryLabel = fixEncoding($result[0]);
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/telephone');
		$europass->telephone = $result[0];
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/fax');
		$europass->fax = $result[0];
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/mobile');
		$europass->mobile = $result[0];
		$result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/email');
		$europass->email = fixEncoding($result[0]);
		$result = $xml->xpath('//europass:learnerinfo/identification/demographics/birthdate');
		$europass->birthdate = $result[0];
		$result = $xml->xpath('//europass:learnerinfo/identification/demographics/gender');
		$europass->gender = $result[0];
		$result = $xml->xpath('//europass:learnerinfo/identification/demographics/nationality/code');
		$europass->nationality = fixEncoding($result[0]);
		
		// application
		$result = $xml->xpath('//europass:learnerinfo/application/label');
		$europass->application = fixEncoding($result[0]);
		
		// education
		$result = $xml->xpath('//europass:learnerinfo/educationlist/education/title');
		$europass->clearMetadata('educationTitles');
		$europass->educationTitles = fixEncoding($result);
		$result = $xml->xpath('//europass:learnerinfo/educationlist/education/skills');
		$europass->clearMetadata('educationSkills');
		$europass->educationSkills = fixEncoding($result);
		
		// language
		$result = $xml->xpath('//europass:learnerinfo/languagelist/language[@xsi:type="europass:mother"]/label');
		$europass->motherLanguage = fixEncoding($result[0]);
		$result = $xml->xpath('//europass:learnerinfo/languagelist/language[@xsi:type="europass:foreign"]/label');
		$europass->clearMetadata('foreignLanguages');
		$europass->foreignLanguages = fixEncoding($result);
		
		// skills
		$result = $xml->xpath('//europass:learnerinfo/skilllist/skill');
		$europass->clearMetadata('skills');
		$europass->skills = fixEncoding($result);
		$result = $xml->xpath('//europass:learnerinfo/skilllist/structured-skill/drivinglicence');
		$europass->clearMetadata('drivinglicences');
		$europass->drivinglicences = $result;

    // Deal with the file
    $file= new ElggFile();
    $file->owner_guid = $_SESSION['user']->getGUID();
    $file->container_guid = $europass->getGUID();
    $file->setFilename("europass/" . $_SESSION['user']->username . 'cv.xml');
    $file->setMimeType('text/xml');
    $file->open("write");
    $file->write($xmlString);
    $file->close();
    $file->save();

		// Keep the file GUID in a europass property
		$europass->file = $file->getGUID();
    
		// Use Europass WebService to get PDF version of the CV
    $client = new SoapClient("http://europass.cedefop.europa.eu/instrumentssrv/services/Instruments?wsdl");
    $content = $client->getDocumentFromCV($xmlString->grabFile(), 'word', 'fr_FR');
    
		// Write Europass CV PDF file
    $pdf= new ElggFile();
    $pdf->owner_guid = $_SESSION['user']->getGUID();
    $pdf->container_guid = $europass->getGUID();
    $pdf->setFilename("europass/" . $_SESSION['user']->username . 'cv.pdf');
    $pdf->setMimeType("application/pdf");
    $pdf->open("write");
    $pdf->write($content);
    $pdf->close();
    $pdf->save();
		
		// Keep the file GUID in a europass property
		$europass->PDFfile = $pdf->getGUID();
    
		// Success message
		system_message(elgg_echo("europass:saved"));
		// Remove the xml cache
		unset($_SESSION['xml']);
		// Special forward to top frame
		js_redirect('pg/europass/' . $_SESSION['user']->username);
		// Avoid any automatic forward
		exit();
  }

  // A way to get out of the iFrame context
  function js_redirect($url) {
    global $CONFIG;
    echo '<script type="text/javascript">'
    .'function getgoing(url)'
    .'{'
    .'  top.location = url;'
    .'}'
    .'if (top.frames.length > 0)'
    .'{'
    .'  getgoing("'. $CONFIG->wwwroot . $url .'");'
    .'}'
    .'</script>';
  }

  // This is not a really nice Hack, but the only one I found usefull
  // The Europass XML is returned with strange encoding when used in french
  function fixEncoding($in_str)
  {
    $search = Array("Ã§","ä§","Ã‡","ã‡","Ã©","ä©","Ã‰","ã‰","Ã¨","ä¨","Ãˆ","ãˆ","Ãª","äª","ÃŠ","ãŠ","Ã«","ä«","Ã‹","ã‹","Ã®","ä®","ÃŽ","ãŽ","Ã¯","ä¯","Ã","ã","Ã¬","ã¬","ÃŒ","ãŒ","Ã²","ä²","Ã’","ã’","Ã´","ä´","Ã”","ã”","Ã¶","ä¶","Ã–","ã–","Ãµ","ãµ","Ã•","ã•","Ã³","ã³","Ã“","ã“","Ã¸","ã¸","Ã˜","ã˜","Ã*","ã*","Ã€","ã€","Ã¢","ä¢","Ã‚","ã‚","Ã¤","ä¤","Ã„","ã„","Ã¥","ä¥","Ã…","ã…","Ã»","ã»","Ã›","ã›","Ã¼","ä¼","Ãœ","ãœ","Ã¹","ã¹","Ã™","ã™","ã±","Ã±","Ã‘","ã‘", "Ã ");
    $replace = Array("ç","ç","Ç","Ç","é","é","É","É","è","è","È","È","ê","ê","Ê","Ê","ë","ë","Ë","Ë","î","î","Î","Î","ï","ï","Ï","Ï","ì","ì","Ì","Ì","ò","ò","Ò","Ò","ô","ô","Ô","Ô","ö","ö","Ö","Ö","õ","õ","Õ","Õ","ó","ó","Ó","Ó","ø","ø","Ø","Ø","à","à","À","À","â","â","Â","Â","ä","ä","Ä","Ä","å","å","Å","Å","û","û","Û","Û","ü","ü","Ü","Ü","ù","ù","Ù","Ù","ñ","ñ","Ñ","Ñ","à");
    
    return str_replace($search, $replace, $in_str);
  }
?>